<?php

namespace App\Http\Controllers\Saleprice;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Saleprice\Saleprice;
use App\Jobs\SaleCoverJob;
use App\Models\Manger\Manger;
use App\Models\SaleCover\SaleCover;
use App\Models\Saleprice\Saleprice as ModelSaleprice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 销售定价
 */
class SalepriceController extends BaseController
{
    /**
     * 基价管理
     */
    public function dopostaddbase(Request $request)
    {
        $req_data = $request->only(['amount', 'limit_weight']);
        $validate = new Saleprice('addbase');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }
        $amount_cent = mathfuncmoney('mul', $req_data['amount'], 100);
        $limit_weight_g = mathfuncmoney('mul', $req_data['limit_weight'], 10000);
        if ($amount_cent < 0) {
            return response()->json(['code' => '001', 'msg' => '销售基价不能小于0']);
        }
        if ($limit_weight_g < 0) {
            return response()->json(['code' => '001', 'msg' => '限制重量不能小于0']);
        }
        DB::beginTransaction();
        try {
            $mangerinfo = $this->mangerinfo;
            $cpid = $mangerinfo['cpid'] ?? 0;
            ModelSaleprice::where(['cpid' => $cpid, 'type' => 'base'])
                ->where('is_del','=', config('constants.is_del.no'))
                ->update(['is_del' => config('constants.is_del.yes'), 'del_at' => time()]);

            $data = [
                'cpid' => $cpid,
                'type' => 'base',
                'name' => '基价',
                'amount' => mathfuncmoney('mul', $req_data['amount'], 100),
                'limit_weight' => mathfuncmoney('mul', $req_data['limit_weight'], 10000),
                'create_at' => time(),
            ];

            ModelSaleprice::create($data);

            //添加公告
            $this->getnowprice($cpid);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '添加成功'], 200);
    }

    /**
     * 加价管理
     */
    public function dopostaddextra(Request $request)
    {
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;

        DB::beginTransaction();
        try {
            ModelSaleprice::where('cpid', $cpid)->where('type', '!=', 'base')
                ->where('is_del','=', config('constants.is_del.no'))
                ->update(['is_del' => config('constants.is_del.yes'), 'del_at' => time()]);

            //仓库
            if ($request['warehouse_name']) {
                $this->handleextra($request['warehouse_name'], 'warehouse_name', $cpid);
            }

            //钢厂
            if ($request['steel_factory_name']) {
                $this->handleextra($request['steel_factory_name'], 'steel_factory_name', $cpid);
            }

            //品种
            if ($request['breed_name']) {
                $this->handleextra($request['breed_name'], 'breed_name', $cpid);
            }

            //材质
            if ($request['archive_material']) {
                $this->handleextra($request['archive_material'], 'archive_material', $cpid);
            }

            //规格1
            if ($request['specs_1']) {
                $this->handleextra($request['specs_1'], 'specs_1', $cpid);
            }

            //规格2
            if ($request['specs_2']) {
                $this->handleextra($request['specs_2'], 'specs_2', $cpid);
            }

            //规格3
            if ($request['specs_3']) {
                $this->handleextra($request['specs_3'], 'specs_3', $cpid);
            }

            //码单
            if ($request['archive_type']) {
                $this->handleextra($request['archive_type'], 'archive_type', $cpid);
            }

            $this->getnowprice($cpid);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '添加成功'], 200);
    }

    /**
     * 处理加价
     */
    public function handleextra($arr, $type, $cpid)
    {
        $arr = is_array($arr) ? $arr : json_decode($arr, true);
        foreach ($arr as $key => $item) {
            //处理正负符号，截取第一位
            $n = substr($item['amount'], 0, 1);
            if ($n == '-') {
                $op = 2;
            } else {
                $op = 1;
            }

            $arr_type[$key] = [
                'cpid' => $cpid,
                'type' => $type,
                'name' => $item['name'],
                'op' => $op,
                'amount' => mathfuncmoney('mul', abs($item['amount']), 100),
                'create_at' => time(),
            ];
        }
        ModelSaleprice::insert($arr_type);
    }

    /**
     * 销售定价信息
     */
    public function dopostinfo()
    {
        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $list = ModelSaleprice::where(['cpid' => $cpid, 'is_del' => config('constants.is_del.no')])->get();
        if ($list) $list = $list->toArray();
        $data = [];
        foreach ($list as $key => $item) {
            if ($item['type'] == 'base') {
                $data['base']['name'] = $item['name'];
                $data['base']['amount'] = $item['amount'] / 100;
                $data['base']['limit_weight'] = $item['limit_weight'] / 10000;
            } else {
                $data[$item['type']][$key]['name'] = $item['name'];
                if ($item['op'] == 2) {
                    $data[$item['type']][$key]['amount'] = -($item['amount'] / 100);
                } else {
                    $data[$item['type']][$key]['amount'] = $item['amount'] / 100;
                }
            }
        }
        foreach ($data as $key => $item) {
            if ($key != 'base') $data[$key] = array_values($item);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $data]);
    }

    /**
     * 基价、加价历史
     */
    public function getlist(Request $request)
    {
        $mangerinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $data = ModelSaleprice::getlist($request, $mangerinfo, $isgetall);
        if ($data['list']) {
            foreach ($data['list'] as $key => $value) {
                $data['list'][$key]['amount'] = $value['amount'] / 100;
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $data]);
    }

    /**
     * 获取最新的基价、加价
     */
    public function getnowprice($cpid)
    {
        $base = $this->getpriceone($cpid, 'base');
        $warehouse_name = $this->getpricelist($cpid, 'warehouse_name');
        if ($warehouse_name) $warehouse_name = $warehouse_name->toArray();
        $steel_factory_name = $this->getpricelist($cpid, 'steel_factory_name');
        if ($steel_factory_name) $steel_factory_name = $steel_factory_name->toArray();
        $breed_name = $this->getpricelist($cpid, 'breed_name');
        if ($breed_name) $breed_name = $breed_name->toArray();
        $archive_material = $this->getpricelist($cpid, 'archive_material');
        if ($archive_material) $archive_material = $archive_material->toArray();
        $specs_1 = $this->getpricelist($cpid, 'specs_1');
        if ($specs_1) $specs_1 = $specs_1->toArray();
        $specs_2 = $this->getpricelist($cpid, 'specs_2');
        if ($specs_2) $specs_2 = $specs_2->toArray();
        $specs_3 = $this->getpricelist($cpid, 'specs_3');
        if ($specs_3) $specs_3 = $specs_3->toArray();
        $archive_type = $this->getpricelist($cpid, 'archive_type');
        if ($archive_type) $archive_type = $archive_type->toArray();

        /***
         *  操盘 票务 统审 采购 销售
         *  2,3,4,6,7
         *
         */
        $mangerlist = Manger::where([
            'cpid' => $cpid,
            'status' => 1
        ])->where(function ($query) {
            $query->WhereRaw('FIND_IN_SET(?,utypes)', [2])
                ->orWhereRaw('FIND_IN_SET(?,utypes)', [3])
                ->orWhereRaw('FIND_IN_SET(?,utypes)', [4])
                ->orWhereRaw('FIND_IN_SET(?,utypes)', [6])
                ->orWhereRaw('FIND_IN_SET(?,utypes)', [7]);
        })->get();
        // WhereRaw('FIND_IN_SET(?,utypes)', [3,4,7])->get();


        // ->whereIn('utypes', [3, 4, 7])->get();
        Log::info('添加公告:' . json_encode($mangerlist, true));
        if ($mangerlist) {
            $warehouse_name_amount = $steel_factory_name_amount = $breed_name_amount = $archive_material_amount = $specs_1_amount = $specs_2_amount = $specs_3_amount = $archive_type_amount = 0;
            $warehouse_name_op = $steel_factory_name_op = $breed_name_op = $archive_material_op = $specs_1_op = $specs_2_op = $specs_3_op = $archive_type_op = '';

            $base_amount = !empty($base->amount) ? $base->amount / 100 : 0;
            $limit_weight = !empty($base->limit_weight) ? $base->limit_weight / 10000 : 0;
            $contents = '基价：' . $base_amount . '; 限制重量: ' . $limit_weight . '; ';

            if ($warehouse_name) {
                foreach ($warehouse_name as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '仓库: ' . $op . $amount . '/';
                }
            }

            if ($steel_factory_name) {
                foreach ($steel_factory_name as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '钢厂: ' . $op . $amount . '/';
                }
            }

            if ($breed_name) {
                foreach ($breed_name as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '品种: ' . $op . $amount . '/';
                }
            }

            if ($archive_material) {
                foreach ($archive_material as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '材质: ' . $op . $amount . '/';
                }
            }

            if ($specs_1) {
                foreach ($specs_1 as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '规格1: ' . $op . $amount . '/';
                }
            }

            if ($specs_2) {
                foreach ($specs_2 as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '规格2: ' . $op . $amount . '/';
                }
            }

            if ($specs_3) {
                foreach ($specs_3 as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '规格3: ' . $op . $amount . '/';
                }
            }

            if ($archive_type) {
                foreach ($archive_type as $item) {
                    $amount = $item['amount'] / 100;
                    $op = $item['op'] == 1 ? '+' : '-';
                    $contents .= $item['name'] . '码单: ' . $op . $amount . '/';
                }
            }

            if ($contents) {
                $contents = substr($contents, 0, -1);
            }

            /***
             * 需要写入的角色，操盘 票务 统审 采购 销售  2025.04.22
             * 2,3,4,6,7
             */
            $mangerUtype = [2, 3, 4, 6, 7];
            $mangerlist = $mangerlist->toArray();
            $data = [];
            foreach ($mangerlist as $item) {
                foreach ($mangerUtype as $mUtype) {
                    if (strpos($item['utypes'], strval($mUtype)) !== false) {
                        $data[] = [
                            'cpid' => $cpid,
                            'manger_id' => $item['id'],
                            'utype' => $mUtype,
                            'contents' => $contents,
                            'create_at' => time(),
                        ];
                    }
                }
                //Notice::create($data);
            }
            DB::table('notice')->insert($data);
        }
        return;
    }

    public function getpricelist($cpid, $type)
    {
        return ModelSaleprice::where([
            'cpid' => $cpid,
            'type' => $type,
            'is_del' => 1
        ])->get();
    }

    public function getpriceone($cpid, $type)
    {
        return ModelSaleprice::where([
            'cpid' => $cpid,
            'type' => $type,
            'is_del' => 1
        ])->first();
    }


    /**
     * 覆盖
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cover(Request $request)
    {

        $mangerinfo = $this->mangerinfo;

        $params = $request->only(['type', 'start_time', 'end_time']);
        $type = $params['type'] ?? 0;
        $cpid = $mangerinfo['cpid'] ?? 0;


        if ($type == 0) {
            return response()->json(['code' => '001', 'msg' => '类型不能为空']);
        }


        $data['type'] = $type;
        $data['start_time'] = $params['start_time']??0;
        $data['end_time'] = $params['end_time']??0;
        $data['cpid'] = $cpid;
        $data['is_del'] = 1;
        $data['create_at'] = time();

        $cover =SaleCover::query()->create($data);

        $id = $cover->id??0;

        SaleCover::query()
            ->where('is_del', 1)
            ->where('id', '<>',$id)
            ->update(['is_del'=>2,'del_at'=>time()]);

        if($id>0){
            dispatch(new SaleCoverJob(['id'=>$id],$this->mangerinfo))->onConnection('redis')->onQueue(SaleCoverJob::QUEUE_JOB);
            //dispatch_sync(new SaleCoverJob(['id'=>$id],$this->mangerinfo));
        }

        return response()->json(['code' => '000', 'msg' => '覆盖成功','data'=>[]]);

    }
}
